package snow.endpoint;

import snow.endpoint.controller.MemCollector;
import snow.endpoint.entity.MemStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author : liqun
 * @createTime : 2022/2/22 14:53
 */
@Endpoint(id = "myEndPoint")
@Component
class MyEndPoint {
    private List<MemStatus> status;
    @Autowired
    private MemCollector memCollector;
    public MyEndPoint(List<MemStatus> status) {
        this.status = status;
    }

    @ReadOperation
    public Object endpointByGet() {
        this.status = memCollector.status;
        //如果status为空，返回默认值
        if (status == null || status.isEmpty()) {
            return "hello world";
        }
        Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>();
        //循环遍历status中的每个MemStatus
        for (MemStatus memStatus : status) {
            //循环遍历每个MemStatus中的status集合（Map）
            for (Map.Entry<String, Object> entry : memStatus.getStatus().entrySet()) {
                //获取result中的指定值（通过）entry的key值并存放入collectList数组集合中
                List<Map<String, Object>> collectList = result.get(entry.getKey());
                //如果collectList为空，创建一个新的数组集合赋给collectList，并为result添加新的键值对(entry.getKey(), collectList)
                if (collectList == null) {
                    collectList = new LinkedList<Map<String, Object>>();
                    result.put(entry.getKey(), collectList);
                }
                Map<String, Object> soloCollect = new HashMap<String, Object>();
                soloCollect.put("date", memStatus.getDate());
                soloCollect.put(entry.getKey(), entry.getValue());
                collectList.add(soloCollect);
            }
        }
        return result;
    }
}